﻿using System;

namespace Sherwood.Imaging.Providers
{
    public class SplitStringProvider : IStringProvider
    {
        private readonly IStringProvider _text;
        private readonly IStringProvider _separator;
        private readonly INumberProvider _segmentIndex;

        public SplitStringProvider(IStringProvider text, string separator, int segmentIndex)
            : this(text, separator, new StaticNumberProvider(segmentIndex))
        {
        }

        public SplitStringProvider(IStringProvider text, string separator, INumberProvider segmentIndex)
            : this(text, new StaticStringProvider(separator), segmentIndex)
        {
        }

        public SplitStringProvider(IStringProvider text, IStringProvider separator, int segmentIndex)
            : this(text, separator, new StaticNumberProvider(segmentIndex))
        {
        }

        public SplitStringProvider(IStringProvider text, IStringProvider separator, INumberProvider segmentIndex)
        {
            _text = text;
            _separator = separator;
            _segmentIndex = segmentIndex;
        }

        public string GetString()
        {
            var text = _text.GetString();
            var separator = _separator.GetString();
            var index = (int)_segmentIndex.GetNumber();
            var splitted = text.Split(new[] { separator }, StringSplitOptions.None);
            return index < splitted.Length ? splitted[index] : null;
        }
    }
}